package com.mobilepay.moneypig.model.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Selection;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.CollectTypeDialog;
import com.mobilepay.moneypig.model.dialog.PaymentWayDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.PayUniData;
import com.mobilepay.moneypig.response.home.PlaceOrderData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.view.WebViewActivity;
import com.mobilepay.moneypig.view.keyboard.DlKeyboard;
import com.mobilepay.moneypig.view.keyboard.KeyboardView;

import java.lang.reflect.Method;

/**
 * Created by xlm on 2017/8/2 0002
 */

public class CollectMoneyActivity extends BaseActivity {
    private static final String TAG = "CollectMoneyActivity";
    private RelativeLayout mRelativeBack;
    private EditText mEditInput;
    private KeyboardView keyboardView;
    private LinearLayout mLinearBank, mLinearAlipay, mLinearWeixin, mLinearMore;
    private DlKeyboard dlKeyboard;
    private TextView mTextRate;
    private TextView mTextProfit;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_collect_money);
    }

    @Override
    protected void initViews() {
        mRelativeBack = (RelativeLayout) findViewById(R.id.collect_back);
        mEditInput = (EditText) findViewById(R.id.collect_num);
        keyboardView = (KeyboardView) findViewById(R.id.keyboard_view);
        mLinearBank = (LinearLayout) findViewById(R.id.collect_bank);
        mLinearAlipay = (LinearLayout) findViewById(R.id.collect_alipay);
        mLinearWeixin = (LinearLayout) findViewById(R.id.collect_weixin);
        mLinearMore = (LinearLayout) findViewById(R.id.collect_more);
        dlKeyboard = (DlKeyboard) findViewById(R.id.dlkeyboard);
        mTextRate = (TextView) findViewById(R.id.collect_rate);
        mTextProfit = (TextView) findViewById(R.id.collect_profit);
    }

    private boolean phoneTextCursor = false;

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        // 设置不调用系统键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(mEditInput, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mEditInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!dlKeyboard.isVisible()) {
                    dlKeyboard.show();
                }
                if (mEditInput.getText().toString().trim().length() > 0) {
                    //设置光标为可见状态
                    mEditInput.setCursorVisible(true);
                    phoneTextCursor = true;
                }
            }
        });

        dlKeyboard.setDlKeyboardListener(new DlKeyboard.OnKeyboardListener() {
            @Override
            public void clickTxt(String txt) {
                String num = mEditInput.getText().toString();
                num += txt;
                CommonUtil.checknum(num, mEditInput);
                mEditInput.setSelection(mEditInput.getText().toString().length());
            }

            @Override
            public void clickConfirm() {
                checkAmount();
            }

            @Override
            public void clickBack() {
                // 点击删除按钮
                String num = mEditInput.getText().toString();
                if (num.length() > 0) {
                    StringBuffer sb = new StringBuffer(mEditInput.getText().toString().trim());
                    int index;
                    if (phoneTextCursor) {
                        index = mEditInput.getSelectionStart();
                        if (index > 0) {
                            sb = sb.delete(index - 1, index);
                        }
                    } else {
                        index = mEditInput.length();
                        if (index > 0) {
                            sb = sb.delete(index - 1, index);
                        }
                    }
                    mEditInput.setText(sb.toString());
                    if (index > 0) {
                        Selection.setSelection(mEditInput.getText(), index - 1);
                    }
                    if (mEditInput.getText().toString().trim().length() <= 0) {
                        mEditInput.setCursorVisible(true);
                        phoneTextCursor = false;
                    }
                }
            }

            @Override
            public void clickDelete() {
                mEditInput.setText("");
            }
        });

    }

    /**
     * 检查输入金额，提交订单申请
     */
    private void checkAmount() {
        String amount = mEditInput.getText().toString();
        if ("0".equals(amount)
                || "0.".equals(amount)
                || "0.0".equals(amount)
                || "0.00".equals(amount)
                || CommonUtil.isEmpty(amount)) {
            showToastShort("请输入有效金额");
        } else {
            showPaymentWayDialog();
        }
    }

//    @Override
//    public void onBackPressed() {
//        if (dlKeyboard.isVisible()) {
//            dlKeyboard.dismiss();
//            return;
//        }
//        super.onBackPressed();
//    }

    private CollectTypeDialog collectTypeDialog;

    private void showPayTypeDialog() {
        if (collectTypeDialog == null) {
            collectTypeDialog = new CollectTypeDialog(getThis());
        }
        collectTypeDialog.setCancelable(true);
        collectTypeDialog.setListener(new CollectTypeDialog.Listener() {
            @Override
            public void onSelectBank() {
                super.onSelectBank();
                CURRENT_TYPE = TYPE_BANK;
                getOrder();
            }

            @Override
            public void onSelectAlipy() {
                super.onSelectAlipy();
                CURRENT_TYPE = TYPE_ALIPAY;
                getOrder();
            }

            @Override
            public void onSelectWeixin() {
                super.onSelectWeixin();
                CURRENT_TYPE = TYPE_WEIXIN;
                getOrder();
            }

            @Override
            public void onSelectMore() {
                super.onSelectMore();
                CURRENT_TYPE = TYPE_MORE;
                showToastShort("更多功能开放中");
            }
        });
        collectTypeDialog.show();
    }

    private PaymentWayDialog mPaymentWayDialog;

    private void showPaymentWayDialog() {
        if (mPaymentWayDialog == null) {
            mPaymentWayDialog = new PaymentWayDialog(getThis());
        }
        mPaymentWayDialog.setCancelable(true);
        mPaymentWayDialog.setListener(new PaymentWayDialog.Listener() {
            @Override
            public void onSelectOne() {
                COLLECT_TYPE = COLLECT_TYPE_ONE;
                showPayTypeDialog();
            }

            @Override
            public void onSelectTwo() {
                COLLECT_TYPE = COLLECT_TYPE_TWO;
                showPayTypeDialog();
            }
        });
        mPaymentWayDialog.show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (collectTypeDialog != null) {
            collectTypeDialog.dismiss();
        }

        if (mPaymentWayDialog != null) {
            mPaymentWayDialog.dismiss();
        }
    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(this);
        mTextRate.setOnClickListener(this);
        mTextProfit.setOnClickListener(this);
    }

    String out_trade_no;
    String amount;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.collect_back:
                finish();
                break;
            case R.id.collect_bank:
                CURRENT_TYPE = TYPE_BANK;
                //是否有信用卡
                if (!CommonUtil.isEmpty(mEditInput.getText().toString())) {
                    dlKeyboard.dismiss();
                    getOrder();
                } else {
                    showToastShort("请输入收款金额");
                }
                break;
            case R.id.collect_alipay:
                CURRENT_TYPE = TYPE_ALIPAY;
                if (!CommonUtil.isEmpty(mEditInput.getText().toString())) {
                    dlKeyboard.dismiss();
                    getOrder();
                } else {
                    showToastShort("请输入收款金额");
                }
                break;
            case R.id.collect_weixin:
                CURRENT_TYPE = TYPE_WEIXIN;
                if (!CommonUtil.isEmpty(mEditInput.getText().toString())) {
                    keyboardView.dismiss();
                    getOrder();
                } else {
                    showToastShort("请输入收款金额");
                }
                break;
            case R.id.collect_more:
                CURRENT_TYPE = TYPE_MORE;
                showToastShort("更多功能开放中");
                break;
            case R.id.collect_rate:
                Intent intent = new Intent();
                intent.setClass(this, WebViewActivity.class);
                intent.putExtra(Key.TITLE, "费率说明");
                intent.putExtra(Key.URL, NetConfig.COLLECT_RATE);
                startActivity(intent);
                break;
            case R.id.collect_profit:
                Intent intent2 = new Intent();
                intent2.setClass(this, WebViewActivity.class);
                intent2.putExtra(Key.TITLE, "会员收益");
                intent2.putExtra(Key.URL, NetConfig.COLLECT_PROFIT);
                startActivity(intent2);
                break;
        }
    }

    private static final int TYPE_BANK = 1;
    private static final int TYPE_ALIPAY = 2;
    private static final int TYPE_WEIXIN = 3;
    private static final int TYPE_MORE = 4;

    private static int CURRENT_TYPE = -1;

    private static int COLLECT_TYPE_ONE = 1;
    private static int COLLECT_TYPE_TWO = 2;

    private int COLLECT_TYPE;

    //下单
    private void getOrder() {
        String uid = String.valueOf(App.getApp().getUserInfo().getData().getUid());
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.getOrder);
        param.add("uid", uid);
        param.add("pay_uid", uid);
        param.add("scene_id", "4");
        param.add("total_amount", mEditInput.getText().toString());
        param.add("sign", param.getMd5String());
        showProgress("下单中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                //订单信息返回后，调用支付宝支付
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 0) {
                        showToastShort(responseResult.getInfo());
                        dismissProgress();
                    } else {
                        PlaceOrderData data = GsonUtil.GsonToBean(string, PlaceOrderData.class);
                        out_trade_no = data.getData().getOut_trade_no();
                        amount = data.getData().getTotal_amount();
                        if (CommonUtil.isEmpty(out_trade_no) || CommonUtil.isEmpty(amount)) {
                            return;
                        }
                        switch (CURRENT_TYPE) {
                            case TYPE_BANK:
                                dismissProgress();
                                Intent intent1 = new Intent();
                                intent1.setClass(CollectMoneyActivity.this, BankPayActivity.class);
                                intent1.putExtra("out_trade_no", out_trade_no);
                                intent1.putExtra("amount", amount);
                                intent1.putExtra("collect_type", COLLECT_TYPE);
                                startActivity(intent1, true);
                                break;
                            case TYPE_ALIPAY:
                                new Handler(getMainLooper()).postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        onSaomaAlipay();
                                    }
                                }, 600);
                                break;
                            case TYPE_WEIXIN:
                                new Handler(getMainLooper()).postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        onSaomaWeixin();
                                    }
                                }, 600);
                                break;
                        }
                    }
                }
            }
        });
    }

    //支付宝
    private void onSaomaAlipay() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", COLLECT_TYPE == COLLECT_TYPE_ONE ? NetConfig.joinpay_uni : NetConfig.helipay_uni);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("out_trade_no", out_trade_no);
        param.add("frp_code", "ALIPAY_NATIVE");
        param.add("sign", param.getMd5String());
        showProgress("二维码生成中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        PayUniData data = GsonUtil.GsonToBean(string, PayUniData.class);
                        String code_url = data.getData().getQrcode_url();
                        Intent intent = new Intent();
                        intent.setClass(CollectMoneyActivity.this, PayCodeActivity.class);
                        intent.putExtra("type", "alipay");
                        intent.putExtra("amount", amount);
                        intent.putExtra("code_url", code_url);
                        startActivity(intent, false);
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }

    //微信
    private void onSaomaWeixin() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", COLLECT_TYPE == COLLECT_TYPE_ONE ? NetConfig.joinpay_uni : NetConfig.helipay_uni);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("out_trade_no", out_trade_no);
        param.add("frp_code", "WEIXIN_NATIVE");
        param.add("sign", param.getMd5String());
        showProgress("二维码生成中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        PayUniData data = GsonUtil.GsonToBean(string, PayUniData.class);
                        String code_url = data.getData().getQrcode_url();
                        Intent intent = new Intent();
                        intent.setClass(CollectMoneyActivity.this, PayCodeActivity.class);
                        intent.putExtra("type", "weixin");
                        intent.putExtra("amount", amount);
                        intent.putExtra("code_url", code_url);
                        startActivity(intent, false);
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
                }
            }
        });
    }
}
